package com.zim.ta_service.base.holder;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.zim.ta_service.base.consts.BaseConstant;
import com.zim.ta_service.base.model.vo.UserContext;
import com.zim.ta_service.support.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * author: alabimofa <br>
 * date: 2021/10/12 18:14 <br>
 */
@Slf4j
public class UserContextHolder {

	public static String getSiteId() {
		return getContext().getSiteId();
	}

	public static String getUserCode() {
		return getContext().getUserCode();
	}

	public static Integer getUserId() {
		return getContext().getUserId();
	}

	public static String getUserName() {
		return getContext().getUserName();
	}

	public static String getLoginUniqueId() {
		return getContext().getLoginUniqueId();
	}

	public static UserContext getContext() {
		if (null != SecurityContextHolder.getContext().getAuthentication() &&
			null != SecurityContextHolder.getContext().getAuthentication().getPrincipal()) {
			Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (principal instanceof UserContext) {
				return (UserContext) principal;
			}
		}

		UserContext ctx = new UserContext();
		if ("local".equals(SpringUtil.getActiveProfile())) {
			HttpServletRequest request = WebUtil.getRequest();
			if (null != request) {
				ctx.setUserId(Convert.toInt(request.getHeader(BaseConstant.USER_ID_HEADER), -1));
				ctx.setUserCode(StrUtil.blankToDefault(request.getHeader(BaseConstant.USER_CODE_HEADER), "UNKNOWN"));
				ctx.setUserName(StrUtil.blankToDefault(request.getHeader(BaseConstant.USER_NAME_HEADER), "UNKNOWN"));
				ctx.setUserId(Convert.toInt(request.getHeader(BaseConstant.USER_ID_HEADER), -1));
				ctx.setSiteId(StrUtil.blankToDefault(request.getHeader(BaseConstant.SITE_ID_HEADER), "UNKNOWN"));
			}
		}

		return ctx;
	}
}
